package com.aspyn.finalproject;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Vibrator;
import android.telephony.SmsMessage;
import android.widget.Toast;

public class TextMessageReceiver extends BroadcastReceiver {

	Context myContext;

	@Override
	public void onReceive(Context context, Intent intent) {
		// TODO Auto-generated method stub

		FinalProjectActivity.numOfMsgs++;
		FinalProjectActivity.msgCount++;

		myContext = context;

		Bundle bundle=intent.getExtras();

		Object[] messages=(Object[])bundle.get("pdus");
		SmsMessage[] sms=new SmsMessage[messages.length];

		for(int n=0;n<messages.length;n++){
			sms[n]=SmsMessage.createFromPdu((byte[]) messages[n]);
		}

		//ADD ADDRESS,MSG TO MESSAGE ARRAY
		TxtMsg tM = new TxtMsg();
		tM.sender = sms[0].getDisplayOriginatingAddress();
		tM.message = sms[0].getDisplayMessageBody();
		FinalProjectActivity.txtMsgStack.push(tM);
		String address = tM.sender;
		String msg = tM.message;
		
		FinalProjectActivity.updateMessageBox(msg,address);
		
		notifyMe(context,address,msg);
	}



	public void notifyMe(Context context, String phoneNum, String message) {
		final NotificationManager mgr = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
		Notification note = new Notification(R.drawable.finalprojecticon,"New Text Message",System.currentTimeMillis());

		PendingIntent i = PendingIntent.getActivity(context, 0, new Intent(context, FinalProjectActivity.class), 0);
		note.setLatestEventInfo(context, "New Txt From " + phoneNum, message, i);

		//    	long[] pattern = {0L,100L,250L,1000L,250L,500L};
		if (FinalProjectActivity.currentVibratePattern[0] != -1) {
			Vibrator vibrator = (Vibrator)context.getSystemService(Context.VIBRATOR_SERVICE);
			vibrator.vibrate(FinalProjectActivity.currentVibratePattern, -1);
		}
		int count = FinalProjectActivity.msgCount;
		note.number = count;

		if (count>1) {
			note.setLatestEventInfo(context, "New Txt From " + phoneNum, count + " new messages", i);
		};

		mgr.notify(FinalProjectActivity.NOTIFY_ME_ID, note);
	}
}